/*******************************************************************************
 ** Name: module.cpp                                                          **
 ** Description:                         **
 **                                                                           **
 ** Open Source Initiative (OSI) Approved License                             **
 **                                                                           **
 ** The contents of this file are subject to the terms of the                 **
 ** Common Development and Distribution License, Version 1.0 only             **
 ** (the "License").  You may not use this file except in compliance          **
 ** with the License.                                                         **
 **                                                                           **
 ** You can find a copy of the license in the LICENSE file within             **
 ** this distribution or at $WIKI/display/ODS/License-software.              **
 ** Software distributed under the License is distributed on an "AS IS"       **
 ** basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.           **
 ** See the License for the specific language governing permissions           **
 ** and limitations under the License.                                        **
 **                                                                           **
 ** When distributing Covered Code, include this CDDL header in each          **
 ** file and include the License file at $GAME_DIR/LICENSE.                   **
 ** If applicable, add the following below this header, with the indicated    **
 ** fields enclosed by brackets "[]" replaced with your own identifying       **
 ** information: Portions Copyright [yyyy] [name of copyright owner]          **
 **                                                                           **
 ** Copyright (c) 2009-2012 Open Design Strategies, LLC                       **
 ** All rights reserved.                                                      **
 ******************************************************************************/
/// Created on March 17, 2010, 8:21 AM
// Modified $Date$ by $Author$
#define module_cpp_ID   "$Id$"

extern "C" {
#include <sys/types.h>
#include <dirent.h>
#include <dlfcn.h>
}
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
using boost::property_tree::ptree;

#include "common.hpp"
#include "module.hpp"
#include "log.hpp"


///////////////////////////////[ Module

Module::Module(const std::string & n)
{
	_name = n;
	_desc = "";
	_loaded = false;
	_lib = 0;
	_uuid = global::UUIDFactory::Create();
}

//bool operator == (const Module & m1, const Module & m2) {
//	return m1.OID() == m2.OID();
//}


//
//void
//Module::GenUUID()
//{
//	boost::uuids::random_generator gen;
//	oid = gen();
//}

///////////////////////////////[ ModuleManager

ModuleManager::ModuleManager()
{

}

ModuleManager::~ModuleManager()
{
	DBGFUNC();
	std::list<Module::pointer>::iterator i;
	for (i = modules.begin(); i != modules.end(); i++)
	{
		Module::pointer mod = *i;
		if (mod->Loaded()) {
			void * lib = mod->Library();
			dlclose(lib);
		}
	}
}

int
ModuleManager::Init()
{
	DBGFUNC();
	int num = 0;
	DIR * dfd, *mfd;
	dirent * dp, *mp;
	ptree pt;
	Module::pointer mod;

	dfd = opendir(DEFAULT_MODULE_DIR);
	for (int c = 0; dp = readdir(dfd); )
	{
		if (strcmp(dp->d_name,".") && strcmp(dp->d_name,".."))
		{
			std::cout << dp->d_name << std::endl;
			mfd = opendir(dp->d_name);
			for (int num = 0; mp = readdir(mfd); )	// maybe a while() ?
			{
				if (!strcmp(mp->d_name,"index.xml")) {
					read_xml(mp->d_name,pt);
					mod = Module::Create();
					mod->Name(pt.get<std::string>("module.name"));
					mod->Version(pt.get<std::string>("module.version"));
					mod->Author(pt.get<std::string>("module.author"));
					mod->Desc(pt.get<std::string>("module.desc"));
					mod->Entry(pt.get<std::string>("module.entry"));
					mod->InitSupplied(pt.get<bool>("module.init"));
					mod->FiniSupplied(pt.get<bool>("module.fini"));
					mod->Location(pt.get<std::string>("module.lib"));
					modules.push_back(mod);
					++num;
				}
//				std::string	buf = mp->d_name;
//				if (!buf.compare(buf.size()-3,3,".so"))
//				{
//
//				}
			}
		}
	}
	return num;
}

typedef void * (*initFunc)();

int
ModuleManager::LoadModule(const std::string & m)
{
	DBGFUNC();
	if (access(m.data(),R_OK))
		return (int)ModError::NonExist;

	std::list<Module::pointer>::const_iterator i;
	for (i = modules.begin(); i != modules.end(); i++) {
		if ((*i)->Name() == m && (*i)->Loaded())
			return (int)ModError::AlreadyLoaded;
	}
	void * lib = dlopen(m.data(),RTLD_NOW|RTLD_GLOBAL);
	if (!lib) {
		debug::log->out(LOG_CRIT,"LoadModule(): %s",dlerror());
		return (int)ModError::Unknown;
	}
	initFunc func = (initFunc)dlsym(lib,(*i)->Entry().data());

	if (!func)
		return (int)ModError::NoEntry;

	(*i)->Library(lib);
	(*i)->Loaded(true);

	return (int)1;
}

int
ModuleManager::LoadModules()
{
	DBGFUNC();
	std::list<Module::pointer>::iterator i;
	for (i = modules.begin(); i != modules.end(); ++i)
	{
		LoadModule((*i)->Name());
	}
	return modules.size();
}

bool
ModuleManager::UnloadModule(const std::string & m)
{
	DBGFUNC();
	std::list<Module::pointer>::iterator i;
	for (i = modules.begin(); i != modules.end(); i++)
	{
		Module::pointer mod = *i;
		if (mod->Loaded() && mod->Name() == m) {
			void * lib = mod->Library();
			dlclose(lib);
			return true;
		}
	}
	return false;
}

void
ModuleManager::Print() const
{

}
